package com.example.bluetoothttss;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.SystemClock;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringJoiner;
import android.graphics.Color;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private Button btnInstructions;
    //private TextView tvLog;
    private TextView tvT1;
    private TextView tvT2;
    private TextView tvSpeed;
    private TextView tvSyl;
    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private StringBuilder historyStringBuilder; // 用于构建历史记录字符串
    private Button btnOpen;
    private int currentState = 0; // 0: 红色, 1: 绿色
    private  Button btnwater;
    private Button btnCoolant;
    private  int flag1=0;//0表示不使用水，1表示使用水
    private  int flag2=0;//0表示不使用冷却液，1表示使用冷却液

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvT1 = findViewById(R.id.tvT1);
        tvT2 = findViewById(R.id.tvT2);
        tvSpeed = findViewById(R.id.tvSpeed);
        tvSyl = findViewById(R.id.tvSyl);
        historyStringBuilder = new StringBuilder(); // 初始化历史记录构建器
       btnwater = findViewById(R.id.btnwater);
       btnCoolant = findViewById(R.id.btnCoolant);
        btnOpen = findViewById(R.id.btn_open);
       btnCoolant.setBackgroundColor(Color.GRAY);
        btnwater.setBackgroundColor(Color.GRAY);
        btnOpen.setBackgroundColor(Color.RED); // 设置为红色
        findViewById(R.id.btnBt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, BtsActivity.class);
                startActivity(intent);
            }
        });
        // 初始化水按钮

        btnwater.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag1 == 0) {
                    btnwater.setBackgroundColor(Color.GREEN);
                    flag1 = 1;

                    // 如果 btnCoolant 是绿色，将其变为灰色
                    if (flag2 == 1) {
                        btnCoolant.setBackgroundColor(Color.GRAY);
                        flag2 = 0;
                    }
                } else {
                    btnwater.setBackgroundColor(Color.GRAY);
                    flag1 = 0;
                }
            }
        });
//初始化冷却液按钮
        btnCoolant.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag2 == 0) {
                    btnCoolant.setBackgroundColor(Color.GREEN);
                    flag2 = 1;

                    // 如果 btnwater 是绿色，将其变为灰色
                    if (flag1 == 1) {
                        btnwater.setBackgroundColor(Color.GRAY);
                        flag1 = 0;
                    }
                } else {
                    btnCoolant.setBackgroundColor(Color.GRAY);
                    flag2 = 0;
                }
            }
        });

        // 初始化开关按钮

        btnOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (currentState) {
                    case 0: // 当前为红色，变为绿色
                        btnOpen.setBackgroundColor(Color.GREEN); // 设置为绿色
                        currentState = 1;
                        break;
                    case 1: // 当前为绿色，变为红色
                        btnOpen.setBackgroundColor(Color.RED); // 设置为红色
                        currentState = 0;
                        break;
                }
            }
        });
    //初始化说明按钮
        Button returnBut = findViewById(R.id.btnInstructions);
        returnBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent re = new Intent(MainActivity.this, Instructions.class);
                startActivity(re);
            }
        });

        // 初始化历史记录按钮
        Button viewHistoryBtn = findViewById(R.id.btnViewHistory);
        viewHistoryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent historyIntent = new Intent(MainActivity.this, HistoryActivity.class);
                historyIntent.putExtra("history_log", historyStringBuilder.toString());
                startActivity(historyIntent);
            }
        });

        BtUtils.getInstance().setOnReadListener(new OnReadListener() {
            @Override
            public void onRead(String read) {
                String t1Final, t2Final, speedFinal, sylFinal;
                try {
                    String[] items = read.split(" ");
                    t1Final = items[0].replace("T1:", "");
                    t2Final = items[1].replace("T2:", "");
                    speedFinal = items[2].replace("SPEED:", "");
                    sylFinal = items[3].replace("SYL:", "");

                    double sylNum = Double.parseDouble(sylFinal);
                    if (sylNum < 3d) {
                        playSoundByMedia();
                    }

                    // 使用final变量
                    final String t1 = t1Final;
                    final String t2 = t2Final;
                    final String spd = speedFinal;
                    final String syl = sylFinal;

                    String time = simpleDateFormat.format(new Date());
                    final String show = time + " 电池温度:" + t1 + "℃"+"液体温度:" + t2 + "℃"+" 液体流速:" + spd + "ml/min"+" 液体剩余量:" + syl + "%";

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvT1.setText(t1+"℃");
                            tvT2.setText(t2+"℃");
                            tvSpeed.setText(spd+"ml/min");
                            tvSyl.setText(syl+"%");
                            //tvLog.append(show + "\r\n"); // 添加到实时日志显示区域
                            //historyStringBuilder.append(show).append("\r\n"); // 同时添加到历史记录构建器
                            historyStringBuilder.append(show);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public long playSoundByMedia() {
        try {
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);
            try {
                AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.di);
                mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(0.50f, 0.50f);
                mediaPlayer.prepare();
                long duration = mediaPlayer.getDuration();
                mediaPlayer.start();
                return duration;
            } catch (IOException e) {
                mediaPlayer = null;
            }
        } catch (Exception e) {
            Log.e(TAG, "Error playing sound", e);
        }
        return 1000;
    }

    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };


}

